package model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;


public class DummyDB {
	
	private List<Object> people;

	public DummyDB() {
		/*
		 * 2013.03.11 - changing ArrayList to LinkedList since the latter 
		 * is optimized for addition or subtraction of items
		 * */
		people = new LinkedList<Object>();
	}
	
	public DummyDB(LinkedList<Object> people) {
		super();
		this.people = people;
	}
	
	public void addPerson(Object p) {
		people.add(p);
		/*System.out.println("addPerson succeeded!\n*************Person added is:\n"
			+ "idPerson: " + p.getId() + ", name: " + p.getName() + ", surname: " 
			+ p.getSurname() + ", Collateral client: " + p.getCc() + ", CC desc: " 
			+ p.getColClient() + ", isChkIC? = " + p.isChkIndirectClient());*/
	}
	
	public void remPerson(int index) {
		people.remove(index);
	}
	
	
	public List<Object> getPeople() {
		// Collections.unmodifiableList prevents other classes from modifying the list by the reference retrieved
		return Collections.unmodifiableList(people);
	}
	
	/*
	 * MVC serialization step 1: create save and load methods for the model
	 * */
	
	/*
	 * command to save table rows to a file
	 * */
	public void saveToFile(File file) throws IOException {
		// fos is needed to open an output stream
		FileOutputStream fos = new FileOutputStream(file);
		// oos is the class that can write the stream
		ObjectOutputStream oos = new ObjectOutputStream(fos);		
		
		/* 
		 * I create an array of the people list, which may seem redundant but
		 * the oos' method use arrays, not lists.
		 */
		Object[] peopleArray = people.toArray(new Object[people.size()]);
		
		oos.writeObject(peopleArray);
		
		// I finally close the stream
		oos.close();
	}
	
	public void loadFromFile(File file) throws IOException, ClassNotFoundException {
		FileInputStream fis = new FileInputStream(file);
		ObjectInputStream ois = new ObjectInputStream(fis);
		
		// I get the info from the db to the peopleArray
		Object[] peopleArray = (Object[]) ois.readObject();
		
		// I first clear the peole ArrayList
		people.clear();
		// Then, I set it with the new value of peopleArray and transform it to a List object
		people.addAll(Arrays.asList(peopleArray));
		
		// I finally close the stream
		ois.close();
	}

}
